package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByUserTrolleyBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.DateUtil;
import com.baseweb.webadmin.core.util.StringUtil;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zx on 2017/6/22.
 * 购物车
 */
@Controller
@RequestMapping("/htmlWeb/")
public class HtmlTrolleyController  extends BaseController {
    private Logger logger = LoggerFactory.getLogger(HtmlTrolleyController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserOrderService userOrderService;

    private String PREFIX = "/htmlWeb/";

    //购物车
    @ResponseBody
    @RequestMapping(value = "/trolleyManage")
    public Map<String, Object> trolleyManage(HttpServletRequest request,@RequestParam(value = "token", defaultValue = "") String token) {

//        if (!validatedRequest(token)){
//            return illegalRequest();
//        }
//
//        User user = currentUser(token);
        Object temp = request.getSession().getAttribute("login_id");
        int userId = temp == null ? 0 : Integer.valueOf(temp.toString());

        List<ByUserTrolleyBvo> byUserTrolleys = userService.selectByUserTrolleyList(userId);

        return success(byUserTrolleys);
    }

    //购物车数量
    @ResponseBody
    @RequestMapping(value = "/trolleySum")
    public Integer trolleySum(HttpServletRequest request,@RequestParam(value = "token", defaultValue = "") String token) {

//        if (!validatedRequest(token)){
//            return illegalRequest();
//        }
//
//        User user = currentUser(token);
        Object temp = request.getSession().getAttribute("login_id");
        int userId = temp == null ? 0 : Integer.valueOf(temp.toString());

        List<ByUserTrolleyBvo> byUserTrolleys = userService.selectByUserTrolleyList(userId);

        return byUserTrolleys == null ? 0 : byUserTrolleys.size();
    }

    @RequestMapping(value = "/deleteTrolley")
    @ResponseBody
    public String deleteTrolley(@RequestParam(value = "trolley_id",required = false) Integer trolley_id,
                                @RequestParam(value = "code",required = false) String code) {

        try{
            if (trolley_id != null && trolley_id > 0) {
                userService.deleteTrolley(trolley_id);
            }
        }catch (Exception e){
            logger.error("删除购物车报错");
            return "error";
        }

        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/addTrolley")
    public Map<String, Object> addTrolley(@RequestParam(value = "biz_user_id",required = false) Integer biz_user_id,
                                          @RequestParam(value = "product_id",required = false) Integer product_id,
                                          @RequestParam(value = "schedule_date",required = false) String schedule_date,
                                          @RequestParam(value = "dinner_type",required = false) String dinner_type,
                                          @RequestParam(value = "descn",required = false) String descn,
                                          @RequestParam(value = "qty_item_1",defaultValue = "1") Integer amount,
                                          HttpServletRequest request) {

        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
        Integer num = null;
        if (product_id != null && product_id > 0) {
            ByUserTrolley byUserTrolley = new ByUserTrolley();
            byUserTrolley.setProductId(product_id);
            byUserTrolley.setUserId(userId);
            if (product_id != null && product_id.intValue() > 0){
                if (biz_user_id != null && biz_user_id.intValue() > 0){
                    byUserTrolley.setBizUserId(biz_user_id);
                }else{
                    byUserTrolley.setBizUserId(userService.findBizProduct(product_id).getUserId());
                }
            }

            if(amount == null || amount < 1){
                amount = 1;
            }

            byUserTrolley.setAmount(amount);

            byUserTrolley.setDescn(descn);
            byUserTrolley.setScheduleDate(DateUtil.getDateTime(schedule_date));
            byUserTrolley.setDinnerType(dinner_type);
            byUserTrolley.setCreateTime(new DateTime());
            byUserTrolley.setUpdateTime(new DateTime());

            num = userService.insertTrolley(byUserTrolley);

        }
        return success("");
    }

    @RequestMapping(value = "/submitOrder")
    @ResponseBody
    public String submitOrder(@RequestParam(value = "ids", required = true) String ids,
                              @RequestParam(value = "payFor",defaultValue = "1") String payFor,
                              @RequestParam(value = "pay_status",defaultValue = "1") Integer pay_status,
                              HttpServletRequest request) {
        String orderIds = "";
        try{
            Object temp = request.getSession().getAttribute("login_id");
            Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());

            Map<Integer, List<ByUserTrolley>> tmpMap = new HashMap<Integer, List<ByUserTrolley>>();
            String[] idArr = ids.split(",");
            if(idArr != null && idArr.length > 0){
                for(String id : idArr){
                    ByUserTrolley current = userService.findTrolley(Integer.valueOf(id));
                    if(tmpMap.containsKey(current.getBizUserId())){
                        tmpMap.get(current.getBizUserId()).add(current);
                    }else{
                        List<ByUserTrolley> tmpList = new ArrayList<ByUserTrolley>();
                        tmpList.add(current);
                        tmpMap.put(current.getBizUserId(), tmpList);
                    }
                    userService.deleteTrolley(Integer.valueOf(id));
                }
            }
            for(Iterator it = tmpMap.keySet().iterator(); it.hasNext();) {
                Integer mKey = (Integer) it.next();

                ByUserOrder order = new ByUserOrder();
                order.setUserId(userId);

                if(StringUtil.isNotBlank(payFor) && "bank".equals(payFor)){
                    order.setPayType(PayType.BANK_PAY.getCode());
                }else{
                    order.setPayType(PayType.ALIPAY.getCode());
                }
                order.setPayStatus(OrderPayStatus.NOT_PAY.getCode());
//                order.setPayStatus(pay_status);
                order.setBizUserId(mKey);
                order.setPrice(BigDecimal.ZERO);
                order.setDeposit(BigDecimal.ZERO);
                order.setNeedPayPrice(BigDecimal.ZERO);
                order.setCreateTime(new DateTime());
                order.setUpdateTime(new DateTime());

                userOrderService.insertByUserOrder(order);
                BigDecimal orderPrice = BigDecimal.ZERO;
                BigDecimal deposit = BigDecimal.ZERO;
                for (ByUserTrolley current : tmpMap.get(mKey)){
                    ByUserBizProduct byUserBizProduct = userService.findBizProduct(current.getProductId());

                    ByUserOrderDetail detail = new ByUserOrderDetail();
                    detail.setOrderId(order.getId());

                    if(current.getAmount() == null || current.getAmount() < 1){
                        detail.setAmount(1);
                    }else{
                        detail.setAmount(current.getAmount());
                    }

                    detail.setUserId(userId);
                    detail.setProductId(current.getProductId());
                    detail.setPrice(byUserBizProduct.getCurrentPrice().multiply(new BigDecimal(current.getAmount())));

                    orderPrice = orderPrice.add(detail.getPrice());

                    detail.setScheduleDate(current.getScheduleDate());
                    detail.setDinnerType(current.getDinnerType());
                    detail.setBizUserId(byUserBizProduct.getUserId());
//                        detail.setOrderId(order.getId());

                    BigDecimal per = byUserBizProduct.getDeposit() == null ? new BigDecimal("0") : byUserBizProduct.getDeposit().divide(new BigDecimal("100"));
                    detail.setDeposit(per.multiply(detail.getPrice()));
                    detail.setCreateTime(new DateTime());
                    detail.setUpdateTime(new DateTime());
                    userOrderService.insertByUserOrderDetail(detail);
                    deposit = deposit.add(detail.getDeposit());
                    //add Schedule
                    ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
                    byUserBizSchedule.setUserId(current.getBizUserId());
                    byUserBizSchedule.setOrderBy(detail.getUserId());
                    byUserBizSchedule.setScheduleDate(detail.getScheduleDate());
                    byUserBizSchedule.setStatus(BaseState.NORMAL.getCode());
                    byUserBizSchedule.setScheduleType(ScheduleType.getByName(detail.getDinnerType()).getCode());
                    byUserBizSchedule.setCreateTime(new DateTime());
                    byUserBizSchedule.setUpdateTime(new DateTime());

                    userOrderService.insertSchedule(byUserBizSchedule);
                }
                ByUserOrder newOrder = userOrderService.findByUserOrder(order.getId());

                //更新订单价格
                newOrder.setPrice(orderPrice);
//                if (currentBizUser.getBizWorkType().intValue() == 1){ //策划师
//                    newOrder.setStatus(OrderStatus.NEW_ORDER.getCode());
//                }else {
                    newOrder.setStatus(OrderStatus.VERIFY_ORDER.getCode());
//                }

//                newOrder.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(newOrder.getPrice()));
                newOrder.setDeposit(deposit);
                newOrder.setNeedPayPrice(newOrder.getPrice().subtract(newOrder.getDeposit()));

                userOrderService.insertByUserOrder(newOrder);
                orderIds += newOrder.getId() + ",";
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return "error";
        }

        return  orderIds;
    }

}
